package handler

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	pb "mpps/services/srv-ProgramDownload/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/program"

	"gorm.io/gorm"
)

type ProgramDownload struct {
}

func NewProgramDownload() *ProgramDownload {
	return &ProgramDownload{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *ProgramDownload) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Mode) <= 0 || len(req.FileType) <= 0 || len(req.Version) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType != program.Js.String() && req.FileType != program.Program.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.Mode != program.Dev.String() && req.Mode != program.Preview.String() && req.Mode != program.Prod.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType == program.Program.String() && len(req.ProgramId) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	model := program.MiniProgram{}
	md5 := common.Md5(fmt.Sprintf("%v-%v-%v", req.FileType, req.Mode, req.Version))
	query := dao.GetDB(ctx).
		Model(&program.MiniProgram{}).
		Where("file_id = ?", md5).
		Limit(1).
		Find(&model)
	var result *gorm.DB
	if query.RowsAffected <= 0 {
		// 查找不到查找最新版本
		if req.Version == "latest" {
			var where string
			switch req.FileType {
			case program.Program.String():
				where = fmt.Sprintf("program_id = '%v' AND mode = '%v' AND file_type = '%v'", req.ProgramId, req.Mode, req.FileType)
			case program.Js.String():
				where = fmt.Sprintf("mode = '%v' AND file_type = '%v'", req.Mode, req.FileType)
			}
			result = dao.GetDB(ctx).
				Model(&program.MiniProgram{}).
				Where(where).
				Order("created_at desc").
				Limit(1).
				Find(&model)
		}
		if result == nil || result.RowsAffected <= 0 {
			return errors.New(common.ErrGetDownload.Message)
		}
	}
	jb, err := json.Marshal(model)
	if err != nil {
		return errors.New(common.ErrGetDownload.Message)
	}
	json.Unmarshal(jb, rsp)
	return nil
}
